﻿using System.Net.WebSockets;
using System.Text;

namespace StudyCompanion.Commons.WebSocket;

public abstract class WebSocketHandler
{
    public WebSocketHandler(WebSocketConnectionManager webSocketConnectionManager)
    {
        WebSocketConnectionManager = webSocketConnectionManager;
    }

    public WebSocketConnectionManager WebSocketConnectionManager { get; set; }

    public virtual void OnConnected(System.Net.WebSockets.WebSocket socket, string key)
    {
        //var ServerSocket = WebSocketConnectionManager.GetWebSocket(key);
        //if (ServerSocket != null)
        //{
        //    WebSocketConnectionManager.AddSocket();
        //    Console.WriteLine("已经存在当前的连接，断开。。");
        //}
        WebSocketConnectionManager.AddSocket(socket, key);
    }

    public virtual async Task OnDisconnected(System.Net.WebSockets.WebSocket socket)
    {
        Console.WriteLine("Socket 断开了");
        await WebSocketConnectionManager.RemoveSocket(WebSocketConnectionManager.GetId(socket));
    }

    public async Task SendMessageAsync(System.Net.WebSockets.WebSocket socket, string message)
    {
        if (socket.State != WebSocketState.Open)
            return;
        var bytes = Encoding.UTF8.GetBytes(message);
        await socket.SendAsync(new ArraySegment<byte>(bytes, 0, bytes.Length), WebSocketMessageType.Text, true,
            CancellationToken.None);
    }

    public async Task SendMessageAsync(string socketId, string message)
    {
        try
        {
            await SendMessageAsync(WebSocketConnectionManager.GetSocketById(socketId), message);
        }
        catch (Exception)
        {
        }
    }

    public async Task SendMessageToAllAsync(string message)
    {
        foreach (var pair in WebSocketConnectionManager.GetAll())
            if (pair.Value.State == WebSocketState.Open)
                await SendMessageAsync(pair.Value, message);
    }

    /// <summary>
    ///     获取一些连接
    /// </summary>
    /// <param name="keys"></param>
    /// <returns></returns>
    public IEnumerable<System.Net.WebSockets.WebSocket> GetSomeWebsocket(string[] keys)
    {
        foreach (var key in keys) yield return WebSocketConnectionManager.GetWebSocket(key);
    }

    /// <summary>
    ///     给一堆人发消息
    /// </summary>
    /// <param name="webSockets"></param>
    /// <param name="message"></param>
    /// <returns></returns>
    public async Task SendMessageToSome(System.Net.WebSockets.WebSocket[] webSockets, string message)
    {
        webSockets.ToList().ForEach(async a => { await SendMessageAsync(a, message); });
    }

    public abstract Task ReceiveAsync(System.Net.WebSockets.WebSocket socket, WebSocketReceiveResult result,
        byte[] buffer);
}